import React, { useEffect, useState, useCallback, forwardRef, useImperativeHandle } from "react";
import './index.less';
import { ImageViewer, Popup, Toast } from 'antd-mobile'
import { Button, Form, Input, Checkbox } from "antd";
import { register, sendCode } from "@/api/Api";

import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();

const Intro = ({ dataSource, isMobile, hideMainPage, ...props }, ref) => {
  const [frameworkVisible, setFrameworkVisible] = useState(false);
  const [frameworkProductVisible, setFrameworkProductVisible] = useState(false);
  const [applicationVisible, setApplicationVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [time, setTime] = useState(59); // timer
  const [form] = Form.useForm();

  useImperativeHandle(ref, () => ({
    goApply
  }));

  useEffect(() => {
    let timer = setInterval(() => {
      if (time > 0 && loading) {
        setTime(time - 1);
      } else {
        setTime(59);
        setLoading(false);
      }
    }, 1000)
    return () => {
      clearInterval(timer)
    }
  }, [time, loading])


  useEffect(()=>{
    window.addEventListener('resize',onResize);
    return (()=>{
      window.removeEventListener('resize',onResize)
    })
  },[])

  const callback = (res) => {
    /* res（验证成功） = {ret: 0, ticket: "String", randstr: "String"}
       res（客户端出现异常错误 仍返回可用票据） = {ret: 0, ticket: "String", randstr: "String", errorCode: Number, errorMessage: "String"}
       res（用户主动关闭验证码）= {ret: 2}
    */
    if (res.ret === 0 && !res.errorCode) {
      setLoading(true);
      submitPhonrVerify(res);
    }
  }

  const loadTencentCaptcha = () => {
    const CaptchaAppId = '2056026228';
    try {
      const captcha = new TencentCaptcha(
        CaptchaAppId,
        callback,
      );
      // captcha.langFun();
      // 滑块显示
      captcha.show();
    } catch (error) {
      loadErrorCallback();
    }
  }

  // 验证码js加载错误处理
  const loadErrorCallback = () => {
    const CaptchaAppId = '2056026228';
     /* 生成票据或自行做其它处理 */
    const ticket = `terror_1001_${  CaptchaAppId  }${Math.floor(new Date().getTime() / 1000)}`;
    callback({
      ret: 0,
      randstr: `@${ Math.random().toString(36).substr(2)}`,
      ticket,
      errorCode: 1001,
      errorMessage: 'jsload_error',
    });
  }

  //兼容大屏手机弹出把表单遮盖
  const onResize = () => {
    const applyform = document.getElementsByClassName("applyPopup");
    if ( document.documentElement.clientHeight <= 440) {
      if (applyform) {
        if ( applyform[0].className.indexOf('scroll') === -1) {
          applyform[0].className = applyform[0].className == '' ? 'scroll' : applyform[0].className + ' ' + 'scroll';
        }
      }
    } else {
      applyform[0].className = applyform[0].className.replace('scroll','');
    }
  }

  const viewFrameworkPic = () => {
    setFrameworkVisible(true);
  }
  const viewFrameworkProductPic = () => {
    setFrameworkProductVisible(true);
  }
  const goApply = () => {
    setApplicationVisible(true);
  }

  const submitRegister = useCallback(async (sendData) => {
    try {
      const res = await register(sendData);
      if (res && res.ok) {
        Toast.show({
          content: res.data || "注册成功，请等待审批",
        })
        setApplicationVisible(false);
      } else {
        Toast.show({
          content: `${res.message || "注册失败"}`,
        })
      }
    } catch (e) {
    }
  }, []);

  const submitPhonrVerify = async({ticket, randstr}) => {
    const {
      getFieldValue,
    } = form;
    const phone = getFieldValue('phone');
    const res = await sendCode({
      phone: (phone || '').trim(),
      ticket,
      randStr: randstr,
    });
    if (res && res.ok) {
      Toast.show({
        content: '短信验证码已发送，注意查看手机',
      })
    }
  }

  // 短信验证
  const verifiedSubmit = async () => {
    const {
      getFieldValue,
    } = form;
    const phone = getFieldValue('phone')
    if (new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/, "g").test(phone)) {
      loadTencentCaptcha();
    } else {
      Toast.show({
        content: '请输入正确手机号码',
      })
    }
  }

  const applySubmit = () => {
    form.validateFields().then(values => {
      if (!values.code) {
        Toast.show({
          content: '请输入正确验证码',
        })
        return false
      }
      if (!values.agreement) {
        Toast.show({
          content: '请勾选协议',
        })
        return false
      }
      submitRegister(values);
    })
    .catch(({values}) => {
      //console.log(values,23321);
    });
  }
  return (
    <div className="intro">
      <div style={{'display': hideMainPage ? 'none':'block'}}>
        <div className="intro_banner">
          <div className="intro_header">
            <img className='intro_logo' src="https://sfservices.obs.cn-south-1.myhuaweicloud.com/sdp-web/startshinex/sfkj_logo.png"></img>
          </div>
          <div className="intro_bottom_content">
            <p className="intro_title">云原生实时数据湖</p>
            {/* <p className="intro_subtitle">致力于降低大数据使用门槛和成本的极致优化</p> */}
          </div>
        </div>
        <div className="intro_wish">
          <p>我们的愿景成为全球领先的独立第三方数据湖厂商；我们的使命让每个客户的数字化更简单、更安全、更高效，为全球数字经济和人类美好生活贡献力量</p>
        </div>
        <div className="intro_pic">
          <p>云原生实时数据湖，打造<span className="blue">存算分离</span>、<span className="blue">实时数仓</span>、<span className="blue">湖仓一体</span>三大核心能力</p>
          {/* <span className="intro_subtitle" style={{marginBottom: 0}}>客户价值：T+1 → T+0</span>
          <span className="intro_subtitle">天下武功，唯快不破，谁的数据结果出得快，谁赢的可能性就越大</span> */}
          <div className="intro_framework" >
            <div>
              <img onClick={viewFrameworkPic} src="https://sfservices.obs.cn-south-1.myhuaweicloud.com/sdp-web/startshinex/h5_framework_new.png"></img>
            </div>
          </div>
        </div>
        <div className="intro_product intro_product_bg">
          <p className="title">新一代云原生实时数据湖引领者</p>
          <div className="intro_list">
            <div className="intro_list_inner">
              <div className="intro_item">
                <img src='https://sfservices.obs.cn-south-1.myhuaweicloud.com/sdp-web/startshinex/h5_list1_new.png'></img>
                <p>实时数据湖</p>
                {/* <p>弹性伸缩</p> */}
              </div>
              <div className="intro_item">
                <img src='https://sfservices.obs.cn-south-1.myhuaweicloud.com/sdp-web/startshinex/h5_list1.png'></img>
                <p>存算分离</p>
                {/* <p>批流一体</p> */}
              </div>
              <div className="intro_item">
                <img src='https://sfservices.obs.cn-south-1.myhuaweicloud.com/sdp-web/startshinex/h5_list2.png'></img>
                <p>湖仓一体</p>
                {/* <p>加速计算</p> */}
              </div>
              <div className="intro_item">
                <img src='https://sfservices.obs.cn-south-1.myhuaweicloud.com/sdp-web/startshinex/h5_list4.png'></img>
                <p>多云管理</p>
                {/* <p>跨云计算</p> */}
              </div>
            </div>
          </div>
          <div className="intro_framework_product">
            <div>
              <img onClick={viewFrameworkProductPic} src="https://sfservices.obs.cn-south-1.myhuaweicloud.com/sdp-web/startshinex/h5_framework_product_new.png"></img>
            </div>
          </div>
        </div>
        <div className="intro_product intro_application">
          <p className="title">应用场景</p>
          <div className="intro_list">
            <div className="intro_list_inner">
              <div className="intro_item intro_item1">
                <p>银行机构实时数据湖升级</p>
              </div>
              <div className="intro_item intro_item2">
                <p>金融企业存算分离改造</p>
              </div>
              <div className="intro_item intro_item3">
                <p>快消零售实时数据湖构建</p>
              </div>
              <div className="intro_item intro_item4">
                <p>跨国企业多云数字化</p>
              </div>
              <div className="intro_item intro_item5">
                <p>大型央国企数字化转型</p>
              </div>
              <div className="intro_item intro_item6">
                <p>物流行业供应链中台改造</p>
              </div>
            </div>
          </div>
        </div>
        <div className="intro_bottom_button" onClick={goApply}>
          <p>申请免费试用</p>
        </div>
      </div>
      <ImageViewer
        image={'https://sfservices.obs.cn-south-1.myhuaweicloud.com/sdp-web/startshinex/h5_framework_new.png'}
        visible={frameworkVisible}
        onClose={() => {
          setFrameworkVisible(false)
        }}
      />
      <ImageViewer
        image={'https://sfservices.obs.cn-south-1.myhuaweicloud.com/sdp-web/startshinex/h5_framework_product_new.png'}
        visible={frameworkProductVisible}
        onClose={() => {
          setFrameworkProductVisible(false)
        }}
      />
      <Popup
        visible={applicationVisible}
        onMaskClick={() => {
          setApplicationVisible(false)
        }}
        afterClose={()=> {
          form.resetFields();
        }}
        bodyClassName='applyPopup'
        bodyStyle={{
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px',
          minHeight: '40vh',
        }}
      >
        <p className="popupTitle">申请免费试用</p>
        <Form
          form={form}
          name="basic"
          initialValues={{ remember: true }}
          autoComplete="off"
          labelAlign="left"
          requiredMark={false}
        >
          <div className="left">
            <Form.Item
              className="item"
              label={
                <span
                >
                  姓名
                </span>
              }
              name="name"
              rules={[
                {
                  required: true,
                  message: "不能为空",
                },
                {
                  max: 50,
                  message: "长度不能超过50",
                },
              ]}
            >
              <Input placeholder="请输入手机号/用户名" />
            </Form.Item>
            <Form.Item
              className="item"
              label="手机号码"
              validateTrigger="onBlur"
              name="phone"
              rules={[
                {
                  required: true,
                  message: "不能为空",
                },
                {
                  pattern: new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/, "g"),
                  message: "请输入正确手机号码",
                },
              ]}
            >
              <Input placeholder="请输入手机号码" />
            </Form.Item>
            <Form.Item
              className="item verifiyCode"
              label="验证码"
              name="code"
              validateTrigger="onBlur"
            >
              <div className="form-box flex">
                <Input placeholder="请输入验证码" />
                <Button disabled={loading} type="primary" className="code" loading={loading} onClick={verifiedSubmit}>
                  {loading ? `${time}秒` : '获取短信验证码'}
                </Button>
              </div>
            </Form.Item>
            <Form.Item
              className="item"
              label="邮箱地址"
              name="email"
              validateTrigger="onBlur"
              rules={[
                {
                  required: true,
                  message: "不能为空",
                },
                {
                  type: "email",
                  message: "邮箱格式错误",
                },
              ]}
            >
              <Input placeholder="请输入邮箱地址" />
            </Form.Item>
            <Form.Item
              className="item"
              label="公司名称"
              validateTrigger="onBlur"
              name="company"
              rules={[
                {
                  required: true,
                  message: "不能为空",
                },
                {
                  max: 50,
                  message: "长度不能超过50",
                },
              ]}
            >
              <Input placeholder="请输入公司名称" />
            </Form.Item>
            <Form.Item
              style={{ marginTop: '10px' }}
              name="agreement"
              valuePropName="checked"
              validateTrigger="onBlur"
            >
              <Checkbox>
                我已阅读并同意{" "}
                <a
                  className="login-form-forgot"
                  href={`${publicRuntimeConfig.basePath}/userservice`}
                  target="_blank"
                >
                  《用户协议》
                </a>
                <span>及</span>
                <a
                  className="login-form-forgot"
                  href={`${publicRuntimeConfig.basePath}/privacypolicy`}
                  target="_blank"
                >
                  《隐私声明》
                </a>
              </Checkbox>
            </Form.Item>
          </div>
        </Form>
        <div className="applyButton" onClick={applySubmit}>提交申请</div>
      </Popup>
    </div>
  );
};

export default forwardRef(Intro);
